package com.scan.bus.presenter;

import android.content.Context;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.scan.bus.SpeechUtils;
import com.scan.bus.bean.BaseEntity;
import com.scan.bus.bean.DeviceContentEntity;
import com.scan.bus.bean.EmptyEntity;
import com.scan.bus.bean.ScanMsgEntity;
import com.scan.bus.util.LogUtil;
import com.scan.bus.util.SharedPrefUtil;
import com.scan.bus.view.IMainView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

public class LocationListenerPresenter extends BasePresenter<IMainView> {
    SpeechUtils speechUtils;
    private long laseTime = 0;

    public LocationListenerPresenter(Context context, IMainView iView, SpeechUtils speechUtils) {
        super(context, iView);
        this.speechUtils = speechUtils;
    }

    @Override
    protected void initApi() {

    }

    @Override
    public void attachView() {

    }

    @Override
    public void detachView() {

    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
        //以下只列举部分获取经纬度相关（常用）的结果信息
        //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
        //获取纬度信息
        double latitude = location.getLatitude();
        //获取经度信息
        double longitude = location.getLongitude();
        //获取定位精度，默认值为0.0f
        float radius = location.getRadius();
        //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
        String coorType = "无";
        LogUtil.httpLogW("getLocType:" + location.getLocType());
        switch (location.getLocType()) {
            case BDLocation.TypeGpsLocation:
                coorType = "gps";
                break;
            case BDLocation.TypeCacheLocation:
                coorType = "缓存定位";
                break;
            case BDLocation.TypeOffLineLocation:
                coorType = "离线定位";
                break;
            case BDLocation.TypeNetWorkLocation:
                coorType = "网络定位";
                break;
            default:
                coorType = "无";
        }
        //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
        int errorCode = location.getLocType();
        String locationTime = location.getTime();

        String addr = location.getAddrStr();    //获取详细地址信息
        String country = location.getCountry();    //获取国家
        String province = location.getProvince();    //获取省份
        String city = location.getCity();    //获取城市
        String district = location.getDistrict();    //获取区县
        String street = location.getStreet();    //获取街道信息
        String adcode = location.getAdCode();    //获取adcode
        String town = location.getTown();    //获取乡镇信息

        long currentTimee = System.currentTimeMillis() / 1000;
//        LogUtil.httpLogW("时间差：:" + (currentTimee-laseTime));
        if (currentTimee - laseTime > 6 && !coorType.equals("无")) {
//            LogUtil.httpLogW("addr:" + addr);
//            speechUtils.speakText(addr);
            Toast.makeText(context, "定位:" + System.currentTimeMillis() / 1000 + "  " + coorType + "  latitude：" + latitude + "  longitude：" + longitude, Toast.LENGTH_LONG).show();
            updateLocation(String.valueOf(latitude), String.valueOf(longitude), System.currentTimeMillis() / 1000 + "", coorType);
            laseTime = currentTimee;
        }
    }


    /**
     * 回调定位诊断信息，开发者可以根据相关信息解决定位遇到的一些问题
     *
     * @param locType           当前定位类型
     * @param diagnosticType    诊断类型（1~9）
     * @param diagnosticMessage 具体的诊断信息释义
     */
    @Override
    public void onLocDiagnosticMessage(int locType, int diagnosticType,
                                       String diagnosticMessage) {
        super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage);
        StringBuffer sb = new StringBuffer(256);
        sb.append("locType:" + locType);
        sb.append("\n" + "诊断结果: ");
        if (locType == BDLocation.TypeNetWorkLocation) {
            if (diagnosticType == 1) {
                sb.append("网络定位成功，没有开启GPS，建议打开GPS会更好" + "\n");
                sb.append(diagnosticMessage);
            } else if (diagnosticType == 2) {
                sb.append("网络定位成功，没有开启Wi-Fi，建议打开Wi-Fi会更好" + "\n");
                sb.append(diagnosticMessage);
            }
        } else if (locType == BDLocation.TypeOffLineLocationFail) {
            if (diagnosticType == 3) {
                sb.append("定位失败，请您检查您的网络状态" + "\n");
                sb.append(diagnosticMessage);
            }
        } else if (locType == BDLocation.TypeCriteriaException) {
            if (diagnosticType == 4) {
                sb.append("定位失败，无法获取任何有效定位依据" + "\n");
                sb.append(diagnosticMessage);
            } else if (diagnosticType == 5) {
                sb.append("定位失败，无法获取有效定位依据，请检查运营商网络或者Wi-Fi网络是否正常开启，尝试重新请求定位" + "\n");
                sb.append(diagnosticMessage);
            } else if (diagnosticType == 6) {
                sb.append("定位失败，无法获取有效定位依据，请尝试插入一张sim卡或打开Wi-Fi重试" + "\n");
                sb.append(diagnosticMessage);
            } else if (diagnosticType == 7) {
                sb.append("定位失败，飞行模式下无法获取有效定位依据，请关闭飞行模式重试" + "\n");
                sb.append(diagnosticMessage);
            } else if (diagnosticType == 9) {
                sb.append("定位失败，无法获取任何有效定位依据" + "\n");
                sb.append(diagnosticMessage);
            }
        } else if (locType == BDLocation.TypeServerError) {
            if (diagnosticType == 8) {
                sb.append("定位失败，请确认您定位的开关打开状态，是否赋予APP定位权限" + "\n");
                sb.append(diagnosticMessage);
            }
        }
//     LogUtil.httpLogW(sb.toString());
    }

    /**
     * 上传定位信息
     */
    public void updateLocation(String latitude, String longitude, String locationTime, String location_type) {
        Map<String, Object> map = new HashMap<>();
        map.put("device_lat", latitude);
        map.put("device_long", longitude);
        map.put("location_time", locationTime);
        map.put("location_type", location_type);
        sortAndMD5(map);
        Call<BaseEntity<EmptyEntity>> baseEntityCall = getAddCookieApiService()
                .locationUp(getRequestBody(map));
        getNetData(baseEntityCall, new SimpleNetDataCallback
                <EmptyEntity>() {
            @Override
            public void onSuccess(BaseEntity<EmptyEntity> entity) {
                super.onSuccess(entity);
            }
        });
    }

    /**
     * 上传扫码的数据信息
     */
    public void updateCodeInfo(String codeData) {
        LogUtil.httpLogW("http" + "扫码请求数据值== > " + codeData);
        SharedPrefUtil.saveCacheSharedPrf("last_code", codeData);
        Map<String, Object> map = new HashMap<>();
        map.put("ticket", codeData);
        sortAndMD5(map);
        Call<BaseEntity<ScanMsgEntity>> baseEntityCall = getAddCookieApiService()
                .checkTicket(getRequestBody(map));
        getNetData(baseEntityCall, new SimpleNetDataCallback
                <ScanMsgEntity>() {
            @Override
            public void onSuccess(BaseEntity<ScanMsgEntity> entity) {
                super.onSuccess(entity);
                if (iView != null) {

                    iView.scanStateShOW(true, entity.msg, entity.data);
                }
            }

            @Override
            public void onError(int code, String message, ScanMsgEntity entity, BaseEntity<ScanMsgEntity> baseEntity) {
                super.onError(code, message, entity, baseEntity);
                if (iView != null) {
                    iView.scanStateShOW(false, message, entity);
                    updateErrCodeInfo(baseEntity, codeData);
                    SharedPrefUtil.saveCacheSharedPrf("last_code", "");
                }
            }
        });
    }


    /**
     * 上传扫码的数据信息
     */
    public void updateErrCodeInfo(BaseEntity<ScanMsgEntity> baseEntity, String code) {
        try {
            List<HashMap<String, String>> listData = new ArrayList<>();
            HashMap<String, String> baseMap = new HashMap<>();
            baseMap.put("url", "Order/checkTicket");
            baseMap.put("error_content", baseEntity.msg + "|" + code);
            listData.add(baseMap);

            ObjectMapper objectMapper = new ObjectMapper();
            String data = objectMapper.writeValueAsString(listData);
            Map<String, Object> map = new HashMap<>();
            map.put("content", data);
            sortAndMD5(map);
            Call<BaseEntity<EmptyEntity>> baseEntityCall = getAddCookieApiService()
                    .addRequestErrorLog(getRequestBody(map));
            getNetData(baseEntityCall, new SimpleNetDataCallback
                    <EmptyEntity>() {
                @Override
                public void onSuccess(BaseEntity<EmptyEntity> entity) {
                    super.onSuccess(entity);
                }
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传本地的二维码数据信息
     */
    public void updateLocalCodeInfo(String code) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("ticket", code);
//        sortAndMD5(map);
//        Call<BaseEntity<ScanMsgEntity>> baseEntityCall = getAddCookieApiService()
//                .checkTicket(getRequestBody(map));
//        getNetData(baseEntityCall, new SimpleNetDataCallback
//                <ScanMsgEntity>() {
//            @Override
//            public void onSuccess(BaseEntity<ScanMsgEntity> entity) {
//                super.onSuccess(entity);
//                if(iView!=null){
//                    iView.localUpdownState(true);
//                }
//            }
//
//            @Override
//            public void onError(int code, String message, ScanMsgEntity entity) {
//                super.onError(code, message, entity);
//                if(iView!=null){
//                    iView.localUpdownState(false);
//                }
//            }
//        });
    }

    /**
     * 上传定位信息
     */
    public void initDeviceInfo() {
        Map<String, Object> map = new HashMap<>();
        sortAndMD5(map);
        Call<BaseEntity<List<DeviceContentEntity>>> baseEntityCall = getAddCookieApiService()
                .deviceInit(map);
        getNetData(baseEntityCall, new SimpleNetDataCallback
                <List<DeviceContentEntity>>() {
            @Override
            public void onSuccess(BaseEntity<List<DeviceContentEntity>> entity) {
                super.onSuccess(entity);
                if (entity.data != null) {
                    iView.initDeviceContent(entity.data);
                }
            }
        });
    }
}
